package cn.hwadee.muying.controller.sys;

import cn.hwadee.muying.commons.base.BaseController;
import cn.hwadee.muying.commons.constant.ConstantWebContext;
import cn.hwadee.muying.commons.utils.Md5Utils;
import cn.hwadee.muying.dto.LayuiResult;
import cn.hwadee.muying.entity.User;
import cn.hwadee.muying.service.UserService;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;

/**
 * Created by Mankind on 2018/4/17.
 */
@Controller
public class LoginController extends BaseController {

    @Autowired
    private UserService userService;

    @RequestMapping(value = "/console/index")
    public String index(){
        return "/sys/index";
    }

    /**
     * 后台登录入口
     * @return
     */
    @RequestMapping(value = {"/sys/login","/"})
    public String loginSystem(){
        return "/sys/login";
    }


    /**
     * flag不为空则为前台登录
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/console/login",produces = "application/json;charset=utf-8", method = RequestMethod.POST)
    @ResponseBody
    public LayuiResult login(String account, String password, String code, Model model, HttpSession session, RedirectAttributes redirectAttributes, String loginPath, Boolean flag) throws Exception {
        LayuiResult result=new LayuiResult();
        //处理验证码
        if (flag==null&&!(code.equalsIgnoreCase(session.getAttribute("code").toString()))) {
            result.setMsg( "验证码错误");
            result.setStatus(LayuiResult.FAIL);
            return result;
        }
        //使用shiro管理登录，会调用到MyRealm.doGetAuthenticationInfo(),可以在里面设置抛出各种异常
        User user=new User();
        try {
            user.setAccount(account);
            user.setPassword(password);
            user.setPassword(new Md5Utils().getkeyBeanofStr(user.getPassword()));
            SecurityUtils.getSubject().login(new UsernamePasswordToken(user.getAccount(), user.getPassword()));
        } catch (Exception e) {
            //可以写跳转的处理异常的页面
            result.setMsg("账号或者密码错误");
            result.setStatus(LayuiResult.FAIL);
            return result;
        }

        //用shiro进行登陆逻辑，这里只需要取user对象放入session中。
        User currentUser = userService.getByAccount(user.getAccount());
        session.setAttribute(ConstantWebContext.request_cUser, currentUser);
        result.setStatus(LayuiResult.OK);

        //判断是否前台，如果是，跳至前台页面，否则进入后台页面
        if(flag!=null){
            //设置访问前台index
            result.setMsg("/main.html");
        }
        else{
            //设置访问后台index
            result.setMsg("/console/main");
        }
        return result;
    }

    /**
     * 前台退出
     * @param session
     * @return
     */
    @RequestMapping(value = "/logout.html", method = RequestMethod.GET)
    public String logout(HttpSession session) {
        try {
            SecurityUtils.getSubject().logout();
        }catch (Exception ex){
            ex.printStackTrace();
        }
        return "redirect:/login.html";
    }

    /**
     * 后台退出
     * @param session
     * @return
     */
    @RequestMapping(value = "/sys/logout.html", method = RequestMethod.GET)
    public String sysLogout(HttpSession session) {
        try {
            SecurityUtils.getSubject().logout();
        }catch (Exception ex){
            ex.printStackTrace();
        }
        return "redirect:/sys/login";
    }
}
